var version = "2.3.0.4";
var alertUsername = "DEFAULT USER";
var customFilters = [];
var favoriteLocations = [];
var customCSS = "";

var combatToggleButton = true;
var draggablePopups = false;
var hideQuestTracker = false;
var hidePreCombatUI = false;
var collectStats = false;
var winScreen = false;
var frontyard = false;
var emoticons = true;
var landscapeAlignment = "left";
var chatHeight = 376;
var chatWidth = 372;
var chatTop = 2;
var chatInputHeight = 52;
var travelHeight = 174;

//JQuery Plugin for toggle click function, replaces deprecated $.fn.toggle
$.fn.toggleClick = function(){

    var functions = arguments ;

    return this.click(function(){
            var iteration = $(this).data('iteration') || 0;
            functions[iteration].apply(this, arguments);
            iteration = (iteration + 1) % functions.length ;
            $(this).data('iteration', iteration);
    });
};

function moveFriendPane(){
	var friendPane = document.getElementById("friendsPane");
	friendPane.style.top = "-230px";
	var interfaceNotice = document.createElement("p");
	interfaceNotice.innerHTML = 'You are using the Very-Unofficial Fleck Landscape Interface extension for Google Chrome.<br>Visit <a href="chrome://extensions" target="new">chrome://extensions</a> to disable or uninstall.';
	var footer = document.getElementById("footer");
	footer.style.top = "-200px";
	footer.insertBefore(interfaceNotice, footer.firstChild);
}

function footerToggle(){
	var toggleButton = $('<div class="button small"><span id="footerToggle">Hide Footer</span></div>');
	toggleButton.toggleClick(
		function(){$("#footer").hide(), $("#footerToggle").text("Show Footer");},
		function(){$("#footer").show(), $("#footerToggle").text("Hide Footer");}
		);
	toggleButton.css({"float":"right", "position":"relative"});
	$("#footer").before(toggleButton);
}

function modifyFooter(){
	$("#footer").remove().css({"font-size":"14px","padding-top":"0px"}).appendTo($("#contentBody"));
	var interfaceNotice = $("<p id=\"landscapeFooter\"></p>");
	interfaceNotice.append("The Very-Unofficial Fleck Landscape extension version "+version+" (")
		.append(settingsLink()).append(").<br>Visit ").append(extensionLink()).append(" to disable or uninstall.");
	interfaceNotice.prependTo("#footer");
	footerToggle();
}

//function to convert an array into the javascript text equivalent, for easy embedding into script tags
function arrayToArrayText(a){
	var text = '[';
	for (var i in a){
		a[i] && (text += ('"'+a[i]+'",') );
	}
	text += ']';
	return text;
}

//embed global variables required in other embedded script files
function embedVariables(){
	var script = document.createElement('script');
	script.setAttribute("type", "text/javascript");
	script.textContent = 'var emoticons = '+emoticons+';\
	var customFilters = '+arrayToArrayText(customFilters)+';\
	var favoriteLocations = '+arrayToArrayText(favoriteLocations)+';\
	var hideCombatWinScreen = '+winScreen+';\
	var frontyard = '+frontyard+';';
	document.head.appendChild(script); 
}

function settingsLink(){
	var optionsPage = chrome.extension.getURL("fancy-settings/source/index.html");
	var settings = $("<a>Settings</a>").click(function(){window.open(optionsPage);});
	return settings;
}

function extensionLink(){
	var extensionLink = $("<a href=\"chrome://extensions\">chrome://extensions</a>");
	return extensionLink;
}

function createLandscapeBar(alignment)
{
	var landscapeBar = $("<div id=\"landscapeBar\"></div>")
			.css({"float":"left", "width":chatWidth+4, "position":"relative", "text-align":"left", "font-size":"11px", "top":"6px"});
	if(alignment=="left"){
		landscapeBar.css("margin-right", "6px");
	}else{
		landscapeBar.css("margin-left", "6px");
	}
	return landscapeBar;
}

function embedScript(jsLink){
	embedjs = chrome.extension.getURL(jsLink);
	var script = document.createElement('script');
	script.setAttribute("type", "text/javascript");
	script.setAttribute("src", embedjs);
	document.head.appendChild(script);
}

function embedChatHooks(){
	embedVariables();
	embedScript("chatHooks.js");
}

function embedEmoticonize(){
	var emojs = "jquery.cssemoticons.min.js";
	var emocss = chrome.extension.getURL("jquery.cssemoticons.css");
	embedScript(emojs);
	$('<link rel="stylesheet" href="'+emocss+'" type="text/css">').appendTo($("head"));
}

function embedEntypo(){
	var entypo = chrome.extension.getURL("entypo.css");
	$('<link rel="stylesheet" href="'+entypo+'" type="text/css">').appendTo($("head"));
}

function geolink(){
 	embedScript("geoUtils.js");
//  	var script = document.createElement('script');
// 	script.setAttribute("type", "text/javascript");
// 	script.setAttribute("src", "http://www.jsommers.com/geoUtils.js?nocache="+Math.random());
// 	document.head.appendChild(script);
}

function rebuildUI(){
	//insert Button Bar *for extra menu buttons as well as reference point for replacement combat UI*
	$('<div id="landscapeButtonBar"></div>').insertAfter("#mapViewportID");
	
	//NEW STUFF
	var gameWidth = "728px"; //also includes small allotment for margins
	$("#gameBorder").contents().wrapAll('<div id="landscapeContainer" />');
	$("#gameBorder").css({"width":"100%", "display":"block", "min-width":"960px","max-width":"1500px", "height":"742px", "box-sizing":"border-box"});
	$("#landscapeContainer").css({"padding-left":gameWidth});
	$("#topBar,#mapViewportID,#landscapeButtonBar").css({"margin-left":"-"+gameWidth, "clear":"left"});
	$("#rightBar").css({"width":"100%", "margin-top": "-66px", "clear":"left"});
	
	$("#chatModule,#chatPaneGroup").css({"width":"100%", "min-width":"210px"});
	
	$("#adminButton").css({"left":"auto", "right":"20px", "z-index":"1"});

	//FIXME: quick fix for expanding chat input width
	customCSS += "#chatTextValuefull, .chatTextValue, #customChatBox{width:80%;}";
	//adjust positioning of visit icon
	customCSS += ".chatLineVisitIcon {margin-top:-11px;\ntop:50%;}";

	//$("#page").css({"min-height":"", "width":770+chatWidth});
	//$("#contentBody").css({"height":600,"float":"left","margin-left":"0px","margin-right":"0px"});
	var landscapeBar;
	//if(landscapeAlignment == "left"){
	//	landscapeBar = createLandscapeBar("left");
	//	$("#contentBody").before(landscapeBar);
		//$("#home-link").css("left","+="+(chatWidth/2+3));
	//} else {
	//	landscapeBar = createLandscapeBar("right");
	//	$("#contentBody").after(landscapeBar);
		//$("#home-link").css("left","-="+(chatWidth/2-3));
	//}
	//move chat to landscape bar
	//landscapeBar.append($("#chatPanelID"));
	//$("#chatTextViewport").css({"height":chatHeight, "width":chatWidth+2});
	//$("#chatShadowWrapId").css({"height":chatHeight-4,"width":chatWidth});
	//$("#chatButton").css({"top":0, "left":0, "position":"relative", "width":chatWidth+2, "margin-left":0, "border-bottom-width":1});
	//chat input size
	//$("#chatTextValue").width(chatWidth-176);
	//chat filter tab size and behavior
	//$("#chatTabViewport").css({"width":chatWidth-88, "overflow":"hidden"});
	
	//modify chat line width
	//$('<style type="text/css">.chatLine{width: 98%}\r#popupFrame_friend{top:222px; z-index:2;}</style>').appendTo("head");
	
	//$("#mapViewportID").height(498);
	//Remove chat placeholder
	//$("#chatTextValue").attr("placeholder", "");
	//$("#directChatPrompt").css("margin-top", -3);
}

var options;
$(document).ready(function() {
	chrome.extension.sendRequest({action: 'flieGetOptions'}, function(theOptions) {
		options = theOptions;
		// The rest of your content script initialization
		combatToggleButton = options['quickSelect'];
		draggablePopups = options['draggable'];
		hideQuestTracker = options['hideQuestTracker'];
		hidePreCombatUI = options['hidePreCombatUI'];
		collectStats = options['statCollection'];
		winScreen = options['winScreen'];
		frontyard = options['frontyard'];
		landscapeAlignment = options['chatAlignment'];
		chatHeight = options['chatHeight'];
		chatWidth = options['chatWidth'];
		emoticons = options['emoticons'];
		customFilters[0] = options['filter1'];
		customFilters[1] = options['filter2'];
		customFilters[2] = options['filter3'];
		favoriteLocations[0] = options['favoriteRestaurant'];
		favoriteLocations[1] = options['favoriteLocation'];
		favoriteLocations[0] || (favoriteLocations[0] = "0");
		
		embedEntypo();
		rebuildUI();
		
		
		//disabled and moved to geoutils
		modifyFooter();
		
		$('<div id="landscapeAlertBar" class="landscape-placeholder"></div>').prependTo("#mapViewportID");
		//test alert notice
		//$('<div class="landscape-alert icon-login icon-left"><span class="friendLink">OHLORDNUTTIN</span></div>').appendTo("#landscapeAlertBar");
		//Status display window
		$('<div id="statusMessage">Status!</div>').appendTo("#landscapeButtonBar").hide();
		embedChatHooks();
		embedEmoticonize();
		draggablePopups && embedScript("draggablePopups.js");
		collectStats && embedScript("statCollection.js?v=22");
		geolink();
		//embed wishing well list
		embedScript("externalContent.js?v=22");
		//embed weather forecasting
		embedScript("weatherForecast.js?v=22");
		//embed extra buttons
		combatToggleButton && embedScript("weaponToggle.js");
		//Hide specific user interface components based on settings
		hideQuestTracker && (customCSS += "#questMeterRowID, #questTrackerPointerID{visibility:hidden;}\n");
		hidePreCombatUI && (customCSS += "#popupFrame_preCombat{visibility:hidden;}\n");
		customCSS += "@font-face {\
    font-family: 'entypo';\
    src: url('"+chrome.extension.getURL("font/entypo.eot")+"');\
    src: url('"+chrome.extension.getURL("font/entypo.eot#iefix")+"') format('embedded-opentype'),\
         url('"+chrome.extension.getURL("font/entypo.woff")+"') format('woff'),\
         url('"+chrome.extension.getURL("font/entypo.ttf")+"') format('truetype'),\
    font-weight: normal;\
    font-style: normal;\
}";
		if(customCSS != "")
		{
			$('<style type="text/css"></style>').html(customCSS).appendTo("head");
		}
	});
});